package com.jpro.module.infra.api.file;

import cn.hutool.core.io.FileUtil;
import com.jpro.framework.common.pojo.CommonResult;
import com.jpro.module.infra.api.file.dto.FileCreateReqDTO;
import com.jpro.module.infra.api.file.dto.ImgCutDto;
import com.jpro.module.infra.api.file.dto.StoreHtmlReqDTO;
import com.jpro.module.infra.api.file.vo.ImgCutVo;
import com.jpro.module.infra.controller.admin.file.image.ImageUtil;
import com.jpro.module.infra.dal.dataobject.file.FileDO;
import com.jpro.module.infra.enums.ResizeMode;
import com.jpro.module.infra.service.file.FileService;
import com.jprocms.module.cms.api.GlobalConfigApi;
import com.jprocms.module.cms.api.dto.GlobalConfigRespVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.File;
import java.nio.file.Files;

import static com.jpro.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.jpro.framework.common.pojo.CommonResult.success;
import static com.jpro.module.infra.enums.ErrorCodeConstants.FILE_CONFIG_NULL;
import static com.jpro.module.infra.enums.ErrorCodeConstants.FILE_NOT_EXISTS;

@Slf4j
@RestController // 提供 RESTful API 接口，给 Feign 调用
@Validated
public class FileApiImpl implements FileApi {

    @Resource
    private FileService fileService;
    @Resource
    private GlobalConfigApi globalConfigApi;

    @Override
    public CommonResult<String> createFile(FileCreateReqDTO createReqDTO) {
        return success(fileService.createFile(createReqDTO.getName(), createReqDTO.getPath(),
                createReqDTO.getContent()));
    }

    @Override
    public CommonResult<ImgCutVo> imageCrop(ImgCutDto params) throws Exception {
        FileDO fileDO = fileService.getFileByUrl(params.url);
        if (fileDO == null) {
            throw exception(FILE_NOT_EXISTS);
        }
        // 图片裁剪。图片任意裁剪，生成新图片。
        String extension = FilenameUtils.getExtension(fileDO.getPath());
        // 读取内容
        byte[] content;
        try {
            content = fileService.getFileContent(fileDO.getConfigId(), fileDO.getPath());
        } catch (Exception e) {
            throw exception(FILE_NOT_EXISTS);
        }
        if (content == null) {
            log.warn("[getFileContent][configId({}) path({}) 文件不存在]", fileDO.getConfigId(), fileDO.getPath());
            throw exception(FILE_NOT_EXISTS);
        }
        //从数据库记录拿到文件
        File file = Files.createTempFile(null, "." + extension).toFile();
        FileUtil.writeBytes(content, file);
        if (file == null) {
            throw exception(FILE_NOT_EXISTS);
        }
        //生成临时文件用于裁剪
        File tempFile = Files.createTempFile(null, "." + extension).toFile();
        try {
            // 裁剪
            if (ResizeMode.scale.equals(params.getMode())) {
                //暂时0.5压缩
                ImageUtil.scale(file.getAbsolutePath(), tempFile.getAbsolutePath(), 0.5f);
            } else if (ResizeMode.resize.equals(params.getMode())) {
                ImageUtil.resize(file.getAbsolutePath(), tempFile.getAbsolutePath(), params.getWidth(), params.getHeight());
            } else {
                ImageUtil.cut(file.getAbsolutePath(), tempFile.getAbsolutePath(), params.getX(), params.getY(), params.getWidth(), params.getHeight());
            }
            final CommonResult<GlobalConfigRespVO> globalConfigRespVOCommonResult = globalConfigApi.getGlobalConfig();
            if(globalConfigRespVOCommonResult.isError()){
                throw exception(FILE_CONFIG_NULL);
            }
            //上传裁剪后的临时文件
            String fileUrl = fileService.createFile(globalConfigRespVOCommonResult.getData().getUploadStoreConfigId().longValue(),fileDO.getName(), fileDO.getPath(), FileUtil.readBytes(tempFile));
            return success(new ImgCutVo(fileUrl));
        } finally {
            if (file.exists()) {
                FileUtils.deleteQuietly(file);
            }
            if (tempFile.exists()) {
                FileUtils.deleteQuietly(tempFile);
            }
        }
    }

    @Override
    public CommonResult<byte[]> getFileContent(String url) {
        return success(fileService.getFileContentByUrl(url));
    }

    @Override
    public void storeHtml(StoreHtmlReqDTO storeHtmlReqDto) throws Exception {
        fileService.storeHtml(storeHtmlReqDto.getFilename(), storeHtmlReqDto.getClientId(), storeHtmlReqDto.getHtmlContent());
    }

    @Override
    public boolean deleteFile(String url, Long clientId) throws Exception {
        return fileService.deleteFile(url, clientId);
    }
}
